package com.tinem.platform.web.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.pojo.co.JwtPropertyName;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className AuthInfoGatewayFilterFactory
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-03 11:18
 */

@Component
public class UserInfoGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> exchange.getPrincipal()
                .cast(JwtAuthenticationToken.class)
                .flatMap(jwtAuthenticationToken -> {
                    String userId = jwtAuthenticationToken.getToken().getClaimAsString(JwtPropertyName.USER_ID);
                    if(StrUtil.isNotEmpty(userId)){
                        exchange.getAttributes().put(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_USER_ID,userId);
                    }
                    return chain.filter(exchange);
                });
    }
}
